import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import {
  loginFormData,
  loginResponseData,
  userInfoResponseData,
} from '@/api/user/type'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import type { UserState } from './types/type'
// 引入常量路由
import { constantRoute } from '@/router/routes'
const useUserStore = defineStore('User', {
  // 存储用户数据
  state: (): UserState => {
    return {
      token: GET_TOKEN() || '', // 用户唯一标识符
      menuRoutes: constantRoute,
      username: '', // 用户名
      avatar: '', // 用户头像
    }
  },
  // 异步、逻辑
  actions: {
    // 用户登录的方法
    async userLogin(data: loginFormData) {
      // 登录请求
      const result: loginResponseData = await reqLogin(data)
      if (result.code === 200) {
        // pinia仓库存储一下token
        // 由于pinia/vuex 存储数据利用的是js对象
        this.token = result.data as string
        // 本地存储持久化存储一份
        SET_TOKEN(this.token)
        return 'ok'
      } else {
        return Promise.reject(new Error(result.data))
      }
    },
    // 获取用户信息
    async userInfo() {
      const result: userInfoResponseData = await reqUserInfo()
      if (result.code === 200) {
        this.username = result.data.name
        this.avatar = result.data.avatar
      }
    },
    // 退出登录
    async logout() {
      await reqLogout()
      this.token = ''
      this.username = ''
      this.avatar = ''
      REMOVE_TOKEN()
    },
  },
  getters: {},
})
export default useUserStore
